<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Inertia\Inertia;
use App\Models\User;
use App\Models\Comment;
use App\Models\Category;
use App\Models\Tag;
use App\Services\PostService;
use App\Services\CategoryService;

/**
 * 后台仪表盘控制器
 * 
 * 职责：
 * - 处理后台仪表盘相关的HTTP请求
 * - 调用服务层获取统计数据
 * - 返回视图
 */
class DashboardController extends Controller
{
    /**
     * 文章服务
     * 
     * @var PostService
     */
    protected PostService $postService;

    /**
     * 分类服务
     * 
     * @var CategoryService
     */
    protected CategoryService $categoryService;

    /**
     * 构造器
     */
    public function __construct(PostService $postService, CategoryService $categoryService)
    {
        $this->postService = $postService;
        $this->categoryService = $categoryService;
    }

    /**
     * 显示仪表盘
     * 
     * @return \Inertia\Response
     */
    public function index()
    {
        // 调用服务层获取统计数据
        $postStats = $this->postService->getDashboardStats();
        
        // 基础统计数据
        $stats = array_merge($postStats, [
            'total_users' => User::count(),
            'total_comments' => Comment::count(),
            'total_categories' => Category::count(),
            'total_tags' => Tag::count(),
        ]);

        // 调用服务层获取其他数据
        $trend = $this->postService->getPublishTrend(30);
        $categoryStats = $this->categoryService->getCategoryStats(5);
        $recentPosts = $this->postService->getRecentPosts(5);
        $popularPosts = $this->postService->getPopularPosts(5);
        
        // 活跃用户
        $activeUsers = User::withCount(['posts', 'comments'])
            ->orderByDesc('posts_count')
            ->limit(5)
            ->get()
            ->map(fn ($user) => [
                'name' => $user->name,
                'posts_count' => $user->posts_count,
                'comments_count' => $user->comments_count,
                'avatar' => $user->profile_photo_url
            ]);

        return Inertia::render('Admin/Dashboard', [
            'stats' => $stats,
            'trend' => $trend,
            'categoryStats' => $categoryStats,
            'recentPosts' => $recentPosts,
            'popularPosts' => $popularPosts,
            'activeUsers' => $activeUsers,
        ]);
    }
} 